import { loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import eslintPlugin from 'vite-plugin-eslint'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import {
  createStyleImportPlugin,
  ElementPlusResolve,
} from 'vite-plugin-style-import'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

function _resolve(dir) {
  return path.resolve(__dirname, dir)
}
export default ({ command, mode }) => {
  const root = process.cwd()
  // 读取.env中配置的环境变量
  const env = loadEnv(mode, root)
  console.log(
    '执行命令: ',
    command,
    ', mode:',
    mode,
    ', env配置文件数据: ',
    env
  )
  const resultConfig = {
    plugins: [
      vue(),
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]',
      }),
      eslintPlugin({
        include: [
          'src/**/*.vue',
          'src/*.ts',
          'src/*.vue',
          'src/*.js',
          'src/**/*.jsx',
          'src/**/*.txs',
          'src/*.jsx',
        ],
        cache: false,
      }),
      // 解决类Message组件样式无法自动引入问题
      createStyleImportPlugin({
        resolves: [ElementPlusResolve()],
        libs: [
          {
            libraryName: 'element-plus',
            esModule: true,
            resolveStyle: name => {
              return `element-plus/theme-chalk/${name}.css`
            },
          },
        ],
      }),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ],
    resolve: {
      alias: {
        '@': _resolve('src'),
      },
    },
  }
  return resultConfig
}
